<?php
namespace app\common\model;

class Mail extends Base
{
	
    protected $insert=['create_time'];

    protected function setCreateTimeAttr(){
    	return time();
    }

    /**
     * 获取分页列表
     * @param  [type] $where    [description]
     * @param  string $queryStr [description]
     * @param  string $baseUrl  [description]
     * @return [type]           [description]
     */
    public function getPageDatas($where){
        // 每页数量
        $perpagenum = isset($where['limit'])?intval($where['limit']):Option::getOne('perpage_default_num');
        unset($where['limit']);
        $perpagenum = $perpagenum>100?100:$perpagenum;
        // 页码
        $page = isset($where['page'])?intval($where['page']):1;
        unset($where['page']);
        $page = $page<1?1:$page;
        $start = ($page-1)*$perpagenum;
        
        $whereData=[];
        if(!empty($where)){
            foreach($where as $k => $wh):
                $whereData['a.'.$k] = $wh;
            endforeach;
        }
        
        $rows = $this
                ->alias('a')
                ->join('member b','a.uid=b.id')
                ->join('member c','a.target=c.id')
                ->where($whereData)
                ->field('a.*,b.mid mid,c.mid target_mid')
                ->limit($start,$perpagenum)
                ->order('a.id','DESC')->select();

        $count = $this->alias('a')->where($whereData)->count();
        $data = [];
        if($count){
            foreach($rows as $row):
                $row = $row->toArray();
                $data[] = $this->setField($row);
            endforeach;
        }

        return [
            'count' => $count,
            'data' => $data
        ];
    }

    /**
     * 处理字段数据
     * @param [type] $row [description]
     */
    public function setField($row){
        if(isset($row['create_time'])){
            $row['create_date'] = date("Y-m-d H:i",$row['create_time']);
        }
        if(isset($row['post_time'])){
            $row['post_date'] = date("Y-m-d H:i",$row['post_time']);
        }
        return $row;
    }
    /**
     * 查询单条发件
     * @param  [type] $id  [description]
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getOneSubject($id){
        $subject = $this
        		->alias('a')
        		->join('member b','a.uid = b.id')
        		->join('member c','a.target = c.id')
        		->where(['a.id'=>$id])
        		->field('a.*,b.mid mid,c.mid target_mid')
        		->find();
        if($subject){
            $subject = $subject->toArray();
            $subject = $this->setField($subject);
        }
        return $subject;
    }

}
